package com.vlin.controller.app;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.annotations.Delete;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.session.Session;
import org.springframework.session.SessionRepository;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.vlin.constains.mode.ModeConstaints;
import com.vlin.entity.device.Device;
import com.vlin.entity.device.DeviceStatu;
import com.vlin.entity.family.Family;
import com.vlin.entity.room.Room;
import com.vlin.entity.user.User;
import com.vlin.errorcode.ErrorCode;
import com.vlin.mapper.device.DeviceMapper;
import com.vlin.mapper.device.DeviceStatusMapper;
import com.vlin.mapper.family.FamilyMapper;
import com.vlin.mapper.family.RoomMapper;
import com.vlin.service.tuya.TuyaService;
import com.vlin.service.user.LoginService;
import com.vlin.util.app.result.ResultUtils;

@RestController
@RequestMapping("app/v1.0")
public class VlinAppController {
	
	private static final Logger logger = org.slf4j.LoggerFactory.getLogger(VlinAppController.class);

	private static final Map<String, Integer> map = new HashMap<>();	
	static {
		
		map.put("kg", 1);
		map.put("cz", 3);
		map.put("pc", 4);
		
		map.put("cjkg", 5);
		map.put("dj", 6);
		
		
		map.put("sd", 9);
		map.put("bh", 10);
		
		map.put("jsq", 11);
		map.put("kt", 12);
		map.put("kj", 13);
		map.put("lyj", 14);
		map.put("qn", 15);
		map.put("ktkzq", 16);
		map.put("cl", 17);
		map.put("wk", 18);
		map.put("fs", 19);
		
		map.put("mcs", 21);
		map.put("sj", 22);
		map.put("wsdcg", 23);
		map.put("pir", 24);
		
		map.put("zd", 25);
		map.put("ylcg", 26);
		map.put("ldcg", 27);
		map.put("ywbj", 28);
		map.put("sgbj", 29);
		map.put("co2bj", 30);
		map.put("wnykq", 32);
	}
	
	
	@SuppressWarnings("rawtypes")
	@Autowired
	private SessionRepository sessionRepository;
	
	@Autowired
	private LoginService loginService;
	
	@Autowired
	private HttpSession session;
	
	@Autowired
	private TuyaService tuyaService;
	
	@Autowired
	private DeviceMapper deviceMapper;
	
	@Autowired
	private DeviceStatusMapper deviceStatuMapper;
	
	@Autowired
	private FamilyMapper familyMapper;
	
	@Autowired
	private RoomMapper roomMapper;


	@SuppressWarnings("unchecked")
	@GetMapping("token")
	public String token(String username, String password) {

		logger.info("SessionId is {}", session.getId());

		Session s = sessionRepository.createSession();
		s.setAttribute("Login", false);
		sessionRepository.save(s);
		String sessionId = loginService.userLogin(username, password, s.getId());
		logger.info("Get sessionId is {}", sessionId);
		Session ssion = sessionRepository.findById(sessionId);
		if (ssion != null && ssion.getAttribute("User") != null) {
			JSONObject result = new JSONObject();
			result.put("sessionId", sessionId);
			return ResultUtils.result(result);
		}
		
		return ResultUtils.result(ErrorCode.USER_NOT_EXIST);

	}
	
	
	//登陆中  密码需要MD5加密；  
	//如何获取token;
	//账号密码获得token
	//获得的token 写在哪里
	//不如仿照涂鸦
	//给每个调接口的用户分配 key和密钥，他们根据这个来调用接口
	

	@GetMapping("tokens/{sessionId}")
	public String tokens(HttpServletRequest request, @PathVariable(name = "sessionId") String sessionId) {
		
	
		Session session = sessionRepository.findById(sessionId);
		return session == null ? "" :(String) session.getAttribute("xixi");
	}
	
	@GetMapping("devices")
	public String getDevices() {
		
		List<Device> list = deviceMapper.findDevByUid(4);
		
		return new JSONArray(list).toString();
	}
	
	@PostMapping("family")
	public String addFamily(@RequestBody Map<String, Object> params) {
		
		String name = (String) params.get("name");
		String ip = (String) params.get("ip");//房间位置 ;
		String rooms = (String) params.get("rooms");
		String token = (String) params.get("token");
		Session session = sessionRepository.findById(token);
		User user = session.getAttribute("User");
		Family family = new Family();
		family.setName(name);
		family.setUid(user.getUid());
		family.setEnabled(1);
		familyMapper.addFamily(family);
		String[] rms = rooms.split(",");
		
		return null;
	}
	
	
	@DeleteMapping("room/{roomId}")
	public String delRoom(@PathVariable(name = "roomId") String roomId) {
		
		
		return null;
	}
	
	@DeleteMapping("family/{familyId}")
	private String deleteFamily(@PathVariable(name = "familyId") String familyId) {
		
		
		
		return null;
	}
	
	@PostMapping("update/family/name")
	private String updateFamilyName(@RequestBody Map<String, Object> params) {
		
		int fid = (int) params.get("fid");
		String name = (String) params.get("name");
		familyMapper.updateFamilyName(name, fid);
		return null;
	}
	
	@GetMapping("device/{did}/function")
	public String getDeviceFunction(@PathVariable(name="did") String did) {
		
		return tuyaService.getDeviceFunction(did);
	}
	
	
	@GetMapping("getAll")
	public String getAllTUYA() {
		
		List<String> uids = getUidList();
		int count = 0;
		
		for(String uid : uids) {
			List<Device> list = getDevicesByUid(uid);
			for(Device device : list) {
				if(deviceMapper.update(device) != 1) {
					deviceMapper.insert(device);
				}
				count++;
			}
			
		}
		return String.valueOf(count);
	}
	
	@GetMapping("updateAllStatus")
	public String update() {
		List<String> uids = getUidList();
		int count = 0;
		
		for(String uid : uids) {
			List<DeviceStatu> list = getDeviceStatus(uid);
			for(DeviceStatu deviceStatu : list) {
				int res = deviceStatuMapper.updateAndDevid(deviceStatu);
				if(res != 1) {
					deviceStatuMapper.insertAndDevid(deviceStatu);
				}
				count++;
			}
			
		}
		return String.valueOf(count);
	}
	
	
	private List<String> getUidList(){
		List<String> uids = new ArrayList<String>();
		JSONObject body = new JSONObject(tuyaService.getUsers(1, 999));
		if(body != null && body.has("success") && body.getBoolean("success")) {
			JSONObject result = body.getJSONObject("result");
			JSONArray list = result.getJSONArray("list");
			if(list != null && list.length() > 0) {
				for(int i = 0; i <list.length(); i ++) {
					JSONObject user = (JSONObject) list.get(i);
					String uid = user.getString("uid");
					uids.add(uid);
				}
			}
		}
		return uids;
	}
	
	private List<DeviceStatu> getDeviceStatus(String uid){
		JSONObject body = new JSONObject(tuyaService.getUserDevice(uid));
		List<DeviceStatu> result = new ArrayList<DeviceStatu>();
		//DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		if(body != null && body.has("success") && body.getBoolean("success")) {
			JSONArray list = body.getJSONArray("result");
			if(list != null && list.length() > 0) {
				for(int i = 0; i <list.length(); i ++) {
					JSONObject device = (JSONObject) list.get(i);
					String did = device.getString("id");
					String devid = deviceMapper.findDevId(did);
					JSONArray commonds = device.getJSONArray("status");
					for(int k = 0; k < commonds.length(); k ++) {
						JSONObject commond = commonds.getJSONObject(k);
						DeviceStatu statu = new DeviceStatu();
						String code = commond.getString("code");
						String value = commond.getString("value");
						statu.setCode(code);
						statu.setConverts("");
						statu.setDid(did);
						statu.setValue(value);
						statu.setDevid(devid);
						result.add(statu);
					}
				}
			}
		}
		
		return result;
	}
	
	private List<Device> getDevicesByUid(String uid){
		
		int fid = 1;
		int disabled = 0; 
		int rid = 1;
		int uuid = 4;
		int mode = ModeConstaints.TUYA_MODE;
		JSONObject body = new JSONObject(tuyaService.getUserDevice(uid));
		List<Device> result = new ArrayList<Device>();
		//DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		if(body != null && body.has("success") && body.getBoolean("success")) {
			JSONArray list = body.getJSONArray("result");
			if(list != null && list.length() > 0) {
				for(int i = 0; i <list.length(); i ++) {
					JSONObject device = (JSONObject) list.get(i);
					String ip = device.has("ip") ? device.getString("ip") : "";
					//long createTime = device.getLong("create_time");
					String timeZone = device.getString("time_zone");
					boolean online = device.getBoolean("online");
					String did = device.getString("id");
					String name = device.getString("name");
					String product_id = device.getString("product_id");
					String puid = device.getString("uid");
					String category = device.getString("category");
					Device dev = new Device();
					dev.setCategory(category);
					dev.setCid(map.containsKey(category) ? map.get(category) : 0);
					dev.setCreate(new Date());
					dev.setDid(did);
					dev.setDisabled(disabled);
					dev.setFid(fid);
					dev.setIp(ip);
					dev.setMode(mode);
					dev.setName(name);
					dev.setOnline(online? 1 : 0);
					dev.setParent(device.getBoolean("sub") ? "1" : "0");
					dev.setPid(product_id);
					dev.setPuid(puid);
					dev.setRid(rid);
					dev.setTime_zone(timeZone);
					dev.setToken("");
					dev.setUid(uuid);
					result.add(dev);
				}
			}
		}
		
		return result;
	}
	
	
	
	
	//获得设备列表
	@GetMapping("device/list")
	public String deviceList() {
		
		return null;
	}
	
}
